package org.example.lettuce;

import io.lettuce.core.RedisClient;
import io.lettuce.core.RedisURI;
import io.lettuce.core.SortArgs;
import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author 宋孟林
 * @description Lettuce 实例的创建和HW，主要练习api的调用
 * @create: 2025/3/7 20:40
 */
public class LettuceHw {
    private static final String MESSAGE = "OK";
    public static void main(String[] args) {
        RedisURI uri = RedisURI.Builder.redis("192.168.100.133")
                .withPort(6379).withAuthentication("default", "123456")
                .build();
        RedisClient redisClient = RedisClient.create(uri);
        StatefulRedisConnection<String, String> connect = redisClient.connect();
        RedisCommands<String, String> commands = connect.sync();
        //string
        String s = commands.set("k6", "v5");
        if (MESSAGE.equals(s)){
            System.out.println("插入成功");
        }else {
            System.out.println("插入失败");
        }
        String v6 = commands.get("k6");
        System.out.println("k6 = " + v6);
        //list
        commands.lpush("myList2", "v2", "v3", "v4");
        List<String> myList2 = commands.lrange("myList2", 0, -1);
        myList2.forEach(System.out::println);

        //set
        commands.sadd("mySet2", "v1", "v2", "v3", "v4");
        Set<String> mySet2 = commands.smembers("mySet2");
        for (String str : mySet2) {
            System.out.println("str = " + str);
        }

        //hash
        HashMap<String, String> hashMap = new HashMap<>(10);
        hashMap.put("k1", "123456");
        hashMap.put("k2", "zhang");
        hashMap.put("k3", "beijing");
        String myHash2 = commands.hmset("myHash2", hashMap);
        if (MESSAGE.equals(myHash2)){
            System.out.println("批量插入成功");
        }else {
            System.out.println("插入失败");
        }

        //zSet
        commands.zadd("myZset2", 100.0, "s1", 110.0, "s3", 130.0, "s4");
        List<String> list = commands.zrange("myZset2", 0, 10);
        for (String item : list) {
            System.out.println("item = " + item);
        }
        //sort 排序，创建排序对象作为sort()方法的参数，调用alpha()方法以字母的形式来比较大小，倒序排序。
        SortArgs sortArgs = new SortArgs();
        sortArgs.alpha();
        sortArgs.desc();
        List<String> list2 = commands.sort("myList2", sortArgs);
        for (String s1 : list2) {
            System.out.println("s1 = " + s1);
        }

        connect.close();
        redisClient.shutdown();
    }
}
